package auth

import (
	"log"
	"net/http"

	"gitee.com/zoneaurora/shop/internal/common"
	"gitee.com/zoneaurora/shop/internal/model"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"golang.org/x/crypto/bcrypt"
)

func Login(c *gin.Context) {
	db := common.DB()

	// 获取请求参数
	var requestUser model.AdminUser
	c.Bind(&requestUser)

	// 验证参数数据
	if len(requestUser.Username) < 4 {
		common.JSON(c, http.StatusUnprocessableEntity,
			"用户名不能少于4位", nil)
		return
	}
	if len(requestUser.Password) < 6 {
		common.JSON(c, http.StatusUnprocessableEntity,
			"密码不能少于6位", nil)
		return
	}

	// 判断用户是否存在
	var adminUser model.AdminUser
	db.Where("username = ?", requestUser.Username).First(&adminUser)
	if adminUser.ID == 0 {
		common.JSON(c, http.StatusUnprocessableEntity,
			"用户不存在", nil)
		return
	}

	// 判断密码是否正确
	err := bcrypt.CompareHashAndPassword([]byte(adminUser.Password), []byte(requestUser.Password))
	if err != nil {
		common.JSON(c, http.StatusBadRequest,
			"密码不正确", nil)
		return
	}

	// 构建token
	token, err := common.GenToken(adminUser)
	if err != nil {
		common.JSON(c, http.StatusInternalServerError,
			"系统异常", nil)
		log.Panicln(err)
		return
	}

	// 发放token
	common.JSON(c, http.StatusOK, "登录成功", gin.H{
		"token": token,
	})
}

func Init(c *gin.Context) {
	db := common.DB()
	username := "admin"
	password := viper.GetString("Admin.Password")

	// 检查用户是否已存在
	var adminUser model.AdminUser
	db.Where("username = ?", username).First(&adminUser)
	if adminUser.ID != 0 {
		adminUser.Password = model.MPassword(password)
		db.Save(&adminUser)
		common.JSON(c, http.StatusOK, "初始化密码成功", nil)
		return
	}

	// 否则创建新用户
	newAdmin := model.AdminUser{
		Username: username,
		Password: model.MPassword(password),
	}
	db.Create(&newAdmin)
	common.JSON(c, http.StatusOK, "初始化密码成功", nil)
}
